<?php
date_default_timezone_set('PRC');
if (!defined('CACHE_PATH'))
	define('CACHE_PATH', str_replace('\\', '/', __DIR__) . '/cache/');

class cache {
	private static $vars = array();
	/**
	 * 缓存变量到文件
	 *
	 * @params string $cache_name 缓存文件名
	 * @params array $vars	缓存变量名称和变量值
	 * @params ini $time	缓存时间(分钟)，0表示无限期
	 *
	 * @return 成功：缓存文件路径，失败：false
	 */
	public static function set($cache_name, $vars = array(), $time = 0) {
		$cache_file_path = CACHE_PATH . $cache_name . '.cache.php';
		if (is_file($cache_file_path) && ($time <= 0 || (($mTime = filemtime($cache_file_path)) && time() <= $mTime + $time * 60)))
			return true;
		if (!is_dir(CACHE_PATH) && !mkdir(CACHE_PATH, 0777, true))
			return false;
		$arr                 = array();
		${'cache_vars_name'} = array_keys($vars);
		$arr[]               = '$cache_vars_name = ' . var_export(${'cache_vars_name'}, true) . ";";
		foreach ($vars as $k => $v) {
			if (empty($k) || !preg_match('/^\w+$/', $k))
				return false;
			$arr[] = '$' . $k . ' = ' . var_export($v, true) . ";";
		}
		$content = "<?php\n";
		$content .= '//缓存创建时间：' . date('Y-m-d H:i:s') . "\n\n";
		$content .= implode("\n\n", $arr);
		$content .= "\n?>";
		return file_put_contents($cache_file_path, $content, LOCK_EX) ? $cache_file_path : false;
	}
	
	/**
	 * 引入缓存文件
	 *
	 * @params string,array $cache_name
	 * @params ini $time	缓存时间(分钟)，0表示无限期
	 * 
	 * @return 成功：缓存文件内的变量（数组），失败：false
	 *
	 */
	public static function get($cache_name, $time = 0) {
		$result = array();
		if (is_array($cache_name)) {
			foreach ($cache_name as $name) {
				$cache_file_path = CACHE_PATH . $name . '.cache.php';
				if (is_file($cache_file_path) && ($time <= 0 || (($mTime = filemtime($cache_file_path)) && time() <= $mTime + $time * 60))) {
					require_once $cache_file_path;
					$arr = array();
					foreach (${'cache_vars_name'} as $var)
						$arr[$var] = ${$var};
					$result[$cache_name] = $arr;
				} else
					@unlink($cache_file_path);
			}
			return count($result) > 0 ? $result : false;
		} else {
			$cache_file_path = CACHE_PATH . $cache_name . '.cache.php';
			if (is_file($cache_file_path) && ($time <= 0 || (($mTime = filemtime($cache_file_path)) && time() <= $mTime + $time * 60))) {
				require_once $cache_file_path;
				if (is_array(${'cache_vars_name'}))
					foreach (${'cache_vars_name'} as $var)
						$result[$var] = ${$var};
				return $result;
			}
			@unlink($cache_file_path);
			return false;
		}
	}
	
	/**
	 * 删除缓存文件
	 *
	 * @params string,array $cache_name
	 *
	 */
	public static function delete($cache_name) {
		if (!is_array($cache_name))
			$cache_name = array(
				$cache_name
			);
		foreach ($cache_name as $name) {
			$cache_file_path = CACHE_PATH . $name . '.cache.php';
			if (is_file($cache_file_path))
				@unlink($cache_file_path);
		}
	}
}
/*var_dump(cache::set('cs', array('v' => '测试'));
include_once(cache::get('cs'));
var_dump($v);*/